package com.chenyi.framework.security.handle;

import com.alibaba.fastjson.JSON;
import com.chenyi.common.constant.Constants;
import com.chenyi.common.core.domain.ApiError;
import com.chenyi.common.core.domain.model.LoginAdmin;
import com.chenyi.common.exception.BadRequestException;
import com.chenyi.common.utils.ServletUtils;
import com.chenyi.common.utils.StringUtils;
import com.chenyi.framework.manager.AsyncManager;
import com.chenyi.framework.manager.factory.AsyncFactory;
import com.chenyi.framework.web.service.AdminTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 * 
 * @author wangkh
 */
@Configuration
public class AdminLogoutSuccessHandlerImpl implements LogoutSuccessHandler
{
    @Autowired
    private AdminTokenService tokenService;

    /**
     * 退出处理
     * 
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException
    {
        LoginAdmin loginAdmin = tokenService.getLoginAdmin(request);
        if (StringUtils.isNotNull(loginAdmin))
        {
            String userName = loginAdmin.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginAdmin(loginAdmin.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordAdminLogininfor(userName, Constants.LOGOUT, "退出成功",loginAdmin.getToken()));
        }
        ServletUtils.renderString(response, JSON.toJSONString(ApiError.error(HttpStatus.OK.value(), "退出成功")));
    }
}
